package com.project.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
@ComponentScan("com.project")
@MapperScan("com.project.mapper")
@EnableTransactionManagement
public class MyBatisConfig {

    //    配置数据源
    @Bean
    public DataSource getData() {
        DruidDataSource data = new DruidDataSource();

        data.setDriverClassName("com.mysql.jdbc.Driver");
        data.setUrl("jdbc:mysql://localhost:3306/email?characterEncoding=utf8&allowMultiQueries=true");
        data.setUsername("root");
        data.setPassword("root");

        data.setMaxActive(100);
        data.setMinIdle(20);
        data.setMaxWait(1000);
        return data;
    }

    //    会话工厂
    @Bean
    public SqlSessionFactoryBean getFactory(DataSource data) {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(data);
        sessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));
        return sessionFactoryBean;
    }

    //    配置事务管理
    @Bean
    public TransactionManager getTransactionManager(DataSource data) {
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(data);
        return manager;

    }

}
